import 'dart:convert';

import 'package:flutter_wear_app/global/audio.dart';
import 'package:flutter_wear_app/global/camera.dart';
import 'package:flutter_wear_app/global/location.dart';
import 'package:flutter_wear_app/global/trtc.dart';
import 'package:flutter_wear_app/utils/event_bus.dart';
import 'package:flutter_wear_app/utils/http_util.dart';
import 'package:flutter_wear_app/utils/mqtt.dart';
import 'package:hive/hive.dart';

late XMqttClient mqttClient;
// 为未初始化的变量添加显式类型注解
final box = Hive.box('myBox');
final LocationService _locationService = LocationService();
final CameraHandler _cameraHandler = CameraHandler();
final AudioHandler _audioHandler = AudioHandler();

late int id;
late Map addressInfo;

Future<void> initBusState() async {
  eventBus.on('hi', (res) {
    final decodedPayload = json.decode(res);
    print('--------------- $decodedPayload');
    print('--------------- $res');

    mqttClient.publish(
      getPublishTopic(decodedPayload['topic']),
      json.encode({
        "time": DateTime.now().millisecondsSinceEpoch,
        "todo": "hello",
      }),
    );
  });

  // 监听拍照
  eventBus.on('takePhoto', (res) async {
    final decodedPayload = json.decode(res);
    await _cameraHandler.takePicture(decodedPayload['cameraId']);
    mqttClient.publish(
      getPublishTopic(decodedPayload['topic']),
      json.encode({
        "time": DateTime.now().millisecondsSinceEpoch,
        "todo": "refresh_photo",
      }),
    );
  });

  // 监听录音
  eventBus.on('takeAudio', (res) async {
    final decodedPayload = json.decode(res);
    await _audioHandler.startRecording();
    mqttClient.publish(
      getPublishTopic(decodedPayload['topic']),
      json.encode({
        "time": DateTime.now().millisecondsSinceEpoch,
        "todo": "refresh_audio",
      }),
    );
  });

  // 监听远程对话
  eventBus.on('takeTrtc', (res) async {
    final decodedPayload = json.decode(res);
    await entRoom();
    mqttClient.publish(
      getPublishTopic(decodedPayload['topic']),
      json.encode({
        "time": DateTime.now().millisecondsSinceEpoch,
        "todo": "linkTrtc",
      }),
    );
  });
}

Future<void> init() async {
  await goLogin();
  await getUserInfo();
  await getAppInfo();
  // 等待mqtt 初始化完成
  await Future.delayed(Duration(seconds: 2));
  mqttClient = XMqttClient.instance;
  print('连接状态   ${jsonEncode(mqttClient.isConnected)}');
  await getFrindeList();
  _locationService.run((Map<String, dynamic> result) {
    addressInfo = result;
  });
}

void disposeAll() {
  // 关闭相机
  _cameraHandler.closeCamera();
  // 关闭定位
  _locationService.cancel();
  // 关闭音频
  _audioHandler.disposeRecorder();
}

Future<void> goLogin() async {
  var res = await HttpUtil.post(
    '/login/account',
    params: {
      'account': 13226092718,
      'scene': 2,
      'terminal': 6,
      'password': "",
      'code': 8888,
    },
  );
  if (res['code'] == 1) {
    box.put('token', res['data']['token']);
    id = res['data']['id'];
  } else {
    print(res['msg']);
  }
}

Future<void> getUserInfo() async {
  var res = await HttpUtil.get('/user/info');
  if (res['code'] == 1) {
    box.put('userInfo', res['data']);
    print(res['data']);
  } else {
    print(res['msg']);
  }
}

Future<void> getAppInfo() async {
  var res = await HttpUtil.get('/app/config', params: {'os': 'android'});
  if (res['code'] == 1) {
    box.put('tencent', res['data']['config']['tencent']);
    var mqtt = res['data']['config']['mqtt'];
    box.put('mqtt', mqtt);
    var host = mqtt['server'];
    var cid = mqtt['clientId'];
    XMqttClient.initialize(
      host: host,
      cid: cid,
      port: 1883,
      username: 'sf_app',
      password: 'giftwl12',
    );
  } else {
    print(res['msg']);
  }
}

Future<void> getFrindeList() async {
  var res = await HttpUtil.get('/friends/friendList');
  if (res['code'] == 1) {
    box.put('subscribe_list', res['data']);

    // 修改部分
    List<String> subArr = [];
    if (res['data'] is List) {
      subArr = (res['data'] as List).map((item) => '${item}_$id').toList();
    }
    subArr.add('system_user_$id');
    // 订阅
    XMqttClient.instance.topicSubscribe(subArr);
    print(res['data']);
  } else {
    print(res['msg']);
  }
}

String getPublishTopic(String topic) {
  final arr = topic.split('_').reversed;
  return arr.join('_');
}

void sendSOS() async {
  HttpUtil.post("/friends/sos", params: {...addressInfo});
}
